#include "tools.h"

#include <cstdio>
#include <iostream>
// CRC
uint16_t Tools::CalculateCRC(const uint8_t* data, size_t length) {
  uint16_t crc = 0xFFFF;
  for (size_t i = 0; i < length; i++) {
    crc ^= data[i];
    for (int j = 0; j < 8; j++) {
      if (crc & 0x0001) {
        crc = (crc >> 1) ^ 0xA001;
      } else {
        crc = crc >> 1;
      }
    }
  }
  return crc;
}

bool Tools::CheckCRC(const std::vector<uint8_t>& data, size_t length) {
  if (length < 2)
    return false;
  // 获取校验码
  std::vector<uint8_t> ret(data.begin(), data.begin() + length);
  uint16_t send_code = ((ret[ret.size() - 1]) << 8 | ret[ret.size() - 2]);
  uint16_t recv_code = CalculateCRC(ret.data(), ret.size() - 2);

  return send_code == recv_code;
}

void Tools::PrintData(const std::vector<uint8_t>& data) {
  for (uint8_t b : data) {
    printf("%02X ", b);
  }
  std::cout << std::endl;
}